<template>
	<view class="background">
		<u-select v-model="gradeShow" mode="single-column" :list="list" @confirm="confirm" value-name="grade" label-name="grade"></u-select>
		<u-modal v-model="removeShow" content="解除绑定会将您当前设备数据删除,确定解除绑定 ?" show-cancel-button @confirm="getrelieveBindParentSn"></u-modal>
		<u-modal v-model="authorizationShow" title="申请设备授权" :title-style="{'font-size':'36rpx', 'font-weight':'600'}" @confirm="getapplyEmpower">
			<view class="slot-content">
				<view class="box box-align-center box-pack-between invite">
					<text>输入班级邀请码</text>
					<u-input placeholder="请输入邀请码" input-align="right" v-model="randCode" />
				</view>
				<u-line color="#e4e7ed" />
				<view class="box box-align-center box-pack-between invite" style="margin-top: 20rpx;">
					<text>老师姓名</text>
					<u-input v-model="randNmae" placeholder="请先填写邀请码" disabled input-align="right" />
				</view>
			</view>
		</u-modal>
		<u-modal v-model="teacherShow" title="解除设备授权" :title-style="{'font-size':'36rpx', 'font-weight':'600'}" @confirm="getrelieveEmpower">
			<view class="slot-content">
				<view class="box box-align-center box-pack-between invite">
					<text>已授权老师</text>
					<u-input placeholder="请输入邀请码" input-align="right" v-model="authorizationName" />
				</view>
			</view>
		</u-modal>
		<u-toast ref="uToast" />
		<view class="vue-content">
			<view class="picture box box-align-center box-pack-between">
				<text class="span">设备头像</text>
				<view class="picture_img" @click="selectFile">
					<img :src="infoForm.avatar" alt />
				</view>
			</view>
			<u-form :model="infoForm" :rules="rules" ref="uForm">
				<view class="" style="background-color: #FFFFFF;margin-top: 20rpx;">
					<u-form-item prop="name" label="设备昵称" label-width="180" :label-style="{'padding-left': '20rpx'}" :border-bottom="false">
						<u-input placeholder="未设置" input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="infoForm.name" />
					</u-form-item>
					<u-form-item prop="username" label="设备号" label-width="180" :label-style="{'padding-left': '20rpx'}" :border-bottom="false">
						<u-input placeholder="未设置" input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="snVlaue" :disabled="true" />
					</u-form-item>
				</view>
				<view class="" style="background-color: #FFFFFF;" v-if="false">
					<u-form-item prop="gradeName" label="年级" label-width="180" :label-style="{'padding-left': '20rpx'}" :border-bottom="false">
						<u-input placeholder="未设置" input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="infoForm.gradeName"
						 @click="selectGrade" :disabled="true" />
						<!-- <u-input input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="infoForm.gradeName" :disabled="true" /> -->
					</u-form-item>
					<u-form-item prop="school" label="学校" label-width="180" :label-style="{'padding-left': '20rpx'}" :border-bottom="false">
						<u-input placeholder="未设置" input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="infoForm.school" />
					</u-form-item>
					<u-form-item label="授权" label-width="180" :label-style="{'padding-left': '20rpx'}" :border-bottom="false" v-if="false">
						<u-input placeholder="未设置" disabled="" input-align="right" :custom-style="{'padding-right': '20rpx'}" v-model="authorizationName" @click="authorizationClick" />
					</u-form-item>
					<view v-if="false" style="margin-left: 20rpx;font-size: 20rpx;letter-spacing: 4rpx;">授权功能说明：您可以自己对平板进行管控，也可以把设备授权给老师进行管理，需要向老师获取邀请码。</view>
				</view>
			</u-form>
			<view class="vue-input remove_border">
				<view class="vue-button relieve_button">
					<button size="large" @click="getupdateParentSn">保存</button>
				</view>
				<view class="vue-button ">
					<button size="large" @click="removeShow = true">解除绑定</button>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		querySnGrade,
		updateParentSn,
		querySnInfo,
		relieveBindParentSn,
		codeGetUsername,
		applyEmpower,
		relieveEmpower
	} from '@/api/myEquipment.js';
	import {
		ossImage,
		ossUploadApk
	} from '@/utils/ossUpload.js';
	import {mapActions} from 'vuex'
	export default {
		data() {
			return {
				removeShow: false, //解绑模拟框
				gradeShow: false, //年级下拉选择
				list: [], //年级数据
				snVlaue: '',
				infoForm: {
					id: 0,
					name: '',
					gradeName: '',
					school: '',
					avatar: ''
				},
				rules: {
					name: [{
						required: true,
						message: '请输入设备名称',
						trigger: ['blur']
					}],
					// gradeName: [{
					// 	required: true,
					// 	message: '请选择年级',
					// 	trigger: ['blur']
					// }],
					// school: [{
					// 	required: true,
					// 	message: '请输入学校',
					// 	trigger: ['blur']
					// }],
				},
				//授权参数
				authorizationShow: false,
				teacherShow: false,
				authorizationName: '',
				randCode: '',
				randNmae: '',
				timeout: null,
				snid: 0
			}
		},
		onLoad(option) {
			this.snid = option.snid
			this.getquerySnInfo(option.snid)
			this.getquerySnGrade()
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		watch: {
			randCode(curVal, oldVal) {
				clearTimeout(this.timeout)
				this.timeout = setTimeout(() => {
					if (curVal != '') {
						this.getcodeGetUsername(curVal)
					}
				}, 1000)
			}
		},
		created() {
			uni.$on('uAvatarCropper', path => {
				this.infoForm.avatar = path;
				uni.uploadFile({
					url: 'https://homework.uiuios.com/admin/accountCenter/uploadAvatar',
					filePath: path,
					name: 'file',
					formData: {
						userId: uni.getStorageSync('userId'),
						lastIp: uni.getStorageSync('Ip')
					},
					success: (res) => {
						this.infoForm.avatar = JSON.parse(res.data).data.imgPath
					}
				});
			})
		},
		methods: {
			...mapActions(['getSnInfoById']),
			//解除绑定
			getrelieveBindParentSn() {
				relieveBindParentSn({
					userId: uni.getStorageSync('userId'),
					lastIp: uni.getStorageSync('Ip'),
					sn: this.snVlaue,
					id: uni.getStorageSync('snId'),
				}).then(res => {
					this.$refs.uToast.show({
						title: res.msg,
						icon: false,
						type: 'success',
						url: '/pages/my/index',
						isTab: true
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 500)
				}).catch(err => {
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
						icon: false
					})
				})
			},
			//根据id查询设备信息
			getquerySnInfo(id) {
				querySnInfo({
					snId: id
				}).then(res => {
					Object.keys(this.infoForm).forEach(key => {
						this.infoForm[key] = res.data[key]
					})
					this.snVlaue = res.data.value
					this.authorizationName = res.data.tUsername
				})
			},
			//保存信息
			getupdateParentSn() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						updateParentSn(this.infoForm).then(res => {
							this.getSnInfoById()
							this.$refs.uToast.show({
								title: res.msg,
								icon: false,
								type: 'success'
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 500)
						}).catch(err => {
							this.$refs.uToast.show({
								title: err.msg,
								type: 'error',
								icon: false
							})
						})
					} else {
						console.log('失败')
						return false
					}
				});
			},
			//跳转裁剪页面
			chooseAvatar() {
				this.$u.route({
					url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					params: {
						// 输出图片宽度，高等于宽，单位px
						destWidth: 300,
						// 裁剪框宽度，高等于宽，单位px
						rectWidth: 200,
						// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
						fileType: 'jpg',
					}
				})
			},
			selectFile() {
				let that = this
				uni.chooseImage({
					count: 1, // 默认最多一次选择9张图
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						let tempFilePaths = res.tempFilePaths; //本地临时路径
						ossImage('picture', tempFilePaths[0]).then(res => {
							console.log("这是上传路径", res)
							that.infoForm.avatar = res
						}).catch(err => {
							that.$refs.uToast.show({
								title: 上传失败,
								icon: false,
								type: 'error'
							})
						})
					}
				})
			},
			//打开年级select视图
			selectGrade() {
				this.gradeShow = !this.gradeShow
			},
			confirm(e) {
				this.infoForm.gradeName = e[0].label
			},
			//获取班级名称
			getquerySnGrade() {
				this.list = [{
						'id': 1,
						'grade': '一年级'
					}, {
						'id': 2,
						'grade': '二年级'
					}, {
						'id': 3,
						'grade': '三年级'
					}, {
						'id': 4,
						'grade': '四年级'
					},
					{
						'id': 5,
						'grade': '五年级'
					}, {
						'id': 6,
						'grade': '六年级'
					}, {
						'id': 7,
						'grade': '初一'
					}, {
						'id': 8,
						'grade': '初二'
					},
					{
						'id': 9,
						'grade': '初三'
					}, {
						'id': 10,
						'grade': '高一'
					}, {
						'id': 11,
						'grade': '高二'
					}, {
						'id': 12,
						'grade': '高三'
					},
				]
			},
			//授权或接触授权click事件
			authorizationClick() {
				if (this.authorizationName) {
					//已授权过
					this.teacherShow = true
				} else {
					//未授权过
					this.authorizationShow = true
				}
			},
			//邀请码获取老师姓名
			getcodeGetUsername(code) {
				codeGetUsername({
					randCode: code
				}).then(res => {
					console.log('成功', res)
					this.randNmae = res.data.username
				}).catch(err => {
					this.randNmae = ''
					this.$refs.uToast.show({
						title: '邀请码有误请重试',
						type: 'error',
						icon: false
					})
				})
			},
			//申请授权
			getapplyEmpower() {
				if (this.randNmae && this.randCode) {
					applyEmpower({
						randCode: this.randCode,
						snCode: this.snVlaue
					}).then(res => {
						this.$refs.uToast.show({
							title: res.msg,
							icon: false,
							type: 'success'
						})
						this.getquerySnInfo(this.snid)
						this.randCode = ''
						this.randNmae = ''
					}).catch(err => {
						this.$refs.uToast.show({
							title: err.msg,
							type: 'error',
							icon: false
						})
					})
				} else {
					this.$refs.uToast.show({
						title: '请先输入邀请码查询到对应老师',
						type: 'error',
						icon: false
					})
				}
			},
			//解除授权
			getrelieveEmpower() {
				// console.log('解除参数',{userId: uni.getStorageSync('userId'), lastIp: uni.getStorageSync('Ip'), id: this.snid})
				relieveEmpower({
					userId: uni.getStorageSync('userId'),
					lastIp: uni.getStorageSync('Ip'),
					id: uni.getStorageSync('snId')
				}).then(res => {
					this.$refs.uToast.show({
						title: res.msg,
						icon: false,
						type: 'success'
					})
					this.getquerySnInfo(this.snid)
					this.randCode = ''
					this.randNmae = ''
				}).catch(err => {
					console.log(err)
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error',
						icon: false
					})
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #FFFFFF;
	}
</style>

<style scoped lang="scss">
	.header {
		height: 50px;
		margin-top: 29px;
		border-radius: 8px;
		margin: 27px 13px auto;
		overflow: hidden;

		.vue-return img {
			height: 30px;
			width: 25px;
			margin-top: 9px;
			display: inline;
			float: left;
		}

		h2 {
			float: left;
			font-size: 16px;
			margin: 12px 20px auto;
			letter-spacing: 1px;
		}
	}

	.vue-content {
		height: 100%;
		margin: 10px 10px 10px 10px;
		overflow: hidden;

		.picture {
			background-color: #fff;
			display: flex;
			padding: 10px;
			justify-content: space-between;
			align-items: center;

			.span {
				font-size: 28rpx;
				line-height: 60px;
				color: #212121;
			}

			.picture_img {
				height: 80px;
				width: 80px;
				border-radius: 50%;
				overflow: hidden;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.vue-input {
			height: 60px;
			padding: 0 10px;
			border-bottom: solid 1px #e1e6ed;
			box-sizing: border-box;

			.span {
				font-size: 16px;
				line-height: 60px;
				color: #212121;
			}

			.vue-input-right {
				float: right;

				label {
					color: #5d5d5d;
					font-size: 14px;
					margin-top: 16px;
					float: right;
					width: 130px;
				}

				/deep/.input {
					color: #5d5d5d;
					float: right;
					width: 130px;
					overflow: hidden;
					font-size: 14px;
					margin-top: 18.5px;
				}

				/deep/ .vue-input-right {
					margin-left: 6px;
				}

				a {
					line-height: 60px;
					letter-spacing: 2px;
					font-size: 16px;
					color: red;
				}

				.span {
					float: right;
					width: 130px;
					overflow: hidden;
					font-size: 16px;
				}

				img {
					height: 17px;
					width: 10px;
					margin-top: 20px;
					margin-right: 10px;
				}

				/deep/.van-popup--top {
					width: 93%;
					// margin: 0 auto;
					// margin-left: 13.6px;
					position: absolute;
					left: 13.6px;
				}

				/deep/.van-cell__title {
					text-align: center;
				}

				/deep/ .van-dropdown-item__option--active {
					text-align: center;
				}

				/deep/.van-dropdown-menu .van-hairline--top-bottom {
					border: none;
				}

				/deep/ .van-ellipsis {
					font-size: 16px;
					color: #797979;
					line-height: normal;
					letter-spacing: 1px;
				}

				/deep/.van-overlay {
					background-color: #f4f4f4;
				}

				/deep/.van-dropdown-menu__title::after {
					border: none;
				}

				/deep/ .van-hairline--top-bottom::after {
					border-width: 0px;
				}

				.name {
					font-size: 16px;
					color: #888888;
				}
			}
		}
	}

	.button {
		background-color: #ffffff;
		border: 1px solid #ffffff;
		border-radius: 8px;
		width: 90%;
		float: left;
		left: 5%;
		letter-spacing: 10px;
		font-weight: 600;
		font-size: 18px;
	}

	.vue-button {
		position: absolute;
		bottom: 70px;
		width: 90%;
		float: left;
		left: 5%;

		button {
			border-radius: $uni-border-radius-lg;
			background-color: #4880ff;
			color: #FFFFFF;
			overflow: hidden;
		}
	}

	.relieve_button {
		bottom: 125px !important;
	}

	/deep/ button[type="primary"] {
		background-color: #fff;
		letter-spacing: 6px;
		color: #5e5e5e;
	}

	.remove_border {
		border: none !important;
	}

	.info-user {
		margin: 10px 0;
		background-color: #fff;
		border-radius: 6px;
	}

	.invite {
		margin-top: 40rpx;
		padding: 0 20rpx;

		text {
			font-size: 28rpx;
			color: #333333;
		}
	}
</style>